package com.wn.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wn.common.ResponseEntity;
import com.wn.entity.User;
import com.wn.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @ author     ：NST
 * @ date       ：Created in 2022/10/25 14:52
 * @ description：权限认证过滤
 * @ modified By：
 * @ version:
 */
@Component
public class AuthenticateFilter implements GlobalFilter, Ordered {
    private JwtUtils jwtUtils = new JwtUtils();
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String login = request.getHeaders().getFirst("release");
        if(login!=null){
            //登录请求直接放行
           return chain.filter(exchange);
        }
        //其他请求需要做权限认证
        //获取请求uri
        String uri = request.getURI().getPath();
        System.out.println("uri:"+uri);
        //从token中获取用户id
        String token = request.getHeaders().getFirst("token");
        //从redis中拿到用户信息 获取权限列表
        String key="user"+jwtUtils.getInfo(token,"id");
        User user =(User) redisTemplate.opsForValue().get(key);
        //将工号存入header,方便后续模块拿取
        request.mutate().header("userWorkNumber",user.getHr().getWorkNumber()).build();
        request.mutate().header("userId",String.valueOf(user.getHr().getId())).build();
        //判断是否拥有权限
        boolean match = user.getRole().getPowerList()
                .stream()
                .anyMatch((power) -> uri.contains(power.getUrl()));
        if(match){
            //拥有权限放行
            return chain.filter(exchange);
        }
        return exchange.getResponse().writeWith(Mono.just(resutl(exchange)));
    }


    public DataBuffer resutl(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        ResponseEntity responseResult = new ResponseEntity("402", "not permit", "没有权限");
        byte[] bytes = null;
        try {
            bytes = new ObjectMapper()
                    .writeValueAsString(responseResult).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
        return dataBuffer;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
